﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JXT.PrimaryKey.Batman.Collections;
using JXT.PrimaryKey.Batman.Domain.Services;
using JXT.PrimaryKey.Batman.Domain.Specifications;
using JXT.PrimaryKey.Batman.Domain.VirtualExchange.Models;
using JXT.PrimaryKey.Batman.Domain.VirtualExchange.Repositories;

namespace JXT.PrimaryKey.Batman.Domain.VirtualExchange.Services.Default
{
    public class BindingTypeService : CachedServiceBase<BindingType>, IBindingTypeService
    {
        private static readonly string _cacheKey = "bindingtype_list";

        #region IBindingTypeService Members

        public void Add(BindingType entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");
            LoadRepository<IBindingTypeRepository>().Add(entity);
            ClearCache();
        }

        public void Update(BindingType entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");
            if (entity.Id <= 0)
                throw new ArgumentException("entity error");
            LoadRepository<IBindingTypeRepository>().Update(entity);
            ClearCache();
        }

        public void Delete(BindingType entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");
            if (entity.Id <= 0)
                throw new ArgumentException("entity error");
            LoadRepository<IBindingTypeRepository>().Delete(entity.Id);
            ClearCache();
        }

        public int Count()
        {
            return GetList().Count();
        }

        public BindingType GetSingle(int id)
        {
            return GetList().FirstOrDefault(e => e.Id == id);
        }

        public IEnumerable<BindingType> GetList()
        {
            var list = Cache.Get(buildCacheKey()) as List<BindingType>;
            if (list == null)
            {
                list = LoadRepository<IBindingTypeRepository>().GetList(null).ToList();
                Cache.Add(buildCacheKey(), list);
            }
            return list;
        }

        public override void ClearCache()
        {
            base.ClearCache();
            Cache.Remove(buildCacheKey());
        }

        #endregion

        private string buildCacheKey()
        {
            return String.Format("{0}_{1}", CacheSpace, _cacheKey);
        }
    }
}
